import 'dart:math';

import 'package:equatable/equatable.dart';
import 'package:excel_utils/pages/week/bean/AccountsReceivableBean.dart';
import 'package:excel_utils/pages/week/bean/AdjustInvoiceBean.dart';
import 'package:excel_utils/pages/week/bean/CustomerAdditionBean.dart';
import 'package:excel_utils/pages/week/bean/OtherOnlineRetailersBean.dart';
import 'package:excel_utils/pages/week/bean/WaiPanZhanBiBean.dart';
import 'package:excel_utils/repository/k8/k8_repository.dart';
import 'package:excel_utils/service/DioManager.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../daily/daily_report/bean/CmcTicketBean.dart';
import '../../../daily/daily_report/bean/CustomerBean.dart';
import '../../../daily/daily_report/bean/DailyInformationBean.dart';
import '../../../daily/daily_report/bean/DailyVoteBean.dart';
import '../../../daily/daily_report/bean/IndependentStatisticalBean.dart';
import '../../../daily/daily_report/bean/LocalDeliveryStatisticsBean.dart';
import '../../../daily/daily_report/bean/SignStatisticsBean.dart';
import '../../../daily/daily_report/bean/ThirdPartyBean.dart';
import '../week_isolate/week_isloate.dart';

part 'week_report_event.dart';

part 'week_report_state.dart';

class WeekReportBloc extends Bloc<WeekReportEvent, WeekReportState> {
  K8Repository k8Repository;

  WeekReportBloc(this.k8Repository) : super(WeekReportInitial()) {
    on<WeekReportEvent>((event, emit) {});
    on<DianShangEvent>((event, emit) async {
      emit(DianShangLoadingState());
      List<String> dianShangMaps = event.dianShangMaps;
      // 多个future 同时执行，拿到所有结果之后再进行下一步操作
      List<Future<SignStatisticsBean>> futuresCurrent = [];
      for (String dianShangCode in dianShangMaps) {
        futuresCurrent.add(k8Repository.querySignStatisticsForDataUrl(maps: {
          "startTime": event.startDate,
          "endTime": event.endDate,
          "timeType": "入场时间",
          "compCode": "",
          "empCode": "$dianShangCode",
          "blGrouping": event.blGrouping
        }));
      }
      List<SignStatisticsBean> currentData = await Future.wait(futuresCurrent);
      for (SignStatisticsBean bean in currentData) {
        print("数据： ${bean.reqCode} ------ ${bean.toJson()} ------");
      }

      if (!event.isQueryLastMonth) {
        // 数据整合
        Map<String, Map<String, dynamic>> resultMaps = {};
        for (var value in dianShangMaps) {
          // 提取当前月份数据
          SignStatisticsBean? currentBean = currentData.firstWhere((element) {
            try {
              return element.reqCode!["empCode"] == value;
            }catch (e) {
              return false;
            }
          });
          // 提取上个月数据
          // SignStatisticsBean? lastMonthBean = lastMonthData.firstWhere((element) => element.reqCode!["empCode"] == value);
          resultMaps[value] = {"currentMonth": currentBean.data, "lastMonth": null};
        }
        emit(DianShangState(currentData: currentData, lastMonthData: currentData, resultMaps: resultMaps));
        return;
      }
      // 上个月的数据 1
      DateTime currentDate = DateTime.parse(event.startDate);
      // 根据当前日期获取上个月1号
      DateTime lastMonthStart = DateTime(currentDate.year, currentDate.month - 1, 1); // 上个月的第一天
      // 上个月的最后一天
      // 先获取当前月份的1号
      DateTime currentMonthStart = DateTime(currentDate.year, currentDate.month, 1); // 当前月的第一天
      DateTime lastMonthEnd = DateTime(currentDate.year, currentDate.month, currentMonthStart.day - 1);

      String lastMonthStartDate = "${lastMonthStart.year}-${lastMonthStart.month.toString().padLeft(2, '0')}-01 00:00:00";
      String lastMonthEndDate = "${lastMonthEnd.year}-${lastMonthEnd.month.toString().padLeft(2, '0')}-${lastMonthEnd.day.toString().padLeft(2, '0')} 23:59:59";
      List<Future<SignStatisticsBean>> futuresLastMonth = [];
      for (String dianShangCode in dianShangMaps) {
        futuresLastMonth.add(k8Repository.querySignStatisticsForDataUrl(maps: {
          "startTime": lastMonthStartDate,
          "endTime": lastMonthEndDate,
          "timeType": "入场时间",
          "compCode": "",
          "empCode": "$dianShangCode",
          "blGrouping": event.blGrouping
        }));
      }
      List<SignStatisticsBean> lastMonthData = await Future.wait(futuresLastMonth);
      for (SignStatisticsBean bean in lastMonthData) {
        print("数据： ${bean.reqCode} ------ ${bean.toJson()} ------");
      }
      // 数据整合
      Map<String, Map<String, dynamic>> resultMaps = {};
      for (var value in dianShangMaps) {
        // 提取当前月份数据
        SignStatisticsBean? currentBean = currentData.firstWhere((element) => element.reqCode!["empCode"] == value);
        // 提取上个月数据
        SignStatisticsBean? lastMonthBean = lastMonthData.firstWhere((element) => element.reqCode!["empCode"] == value);
        resultMaps[value] = {
          "currentMonth": currentBean.data,
          "lastMonth": lastMonthBean.data,
        };
      }
      emit(DianShangState(currentData: currentData, lastMonthData: lastMonthData, resultMaps: resultMaps));
    });

    on<RINCOSEvent>((event, emit) async {
      emit(const RincosLoadingState());

      List<String> accountNo = event.accountNo;
      Map<String, List<AccountData>> mapsResult = {};
      Map<String, String> mapsFail = {};
      for (var action in accountNo) {
        AccountsReceivableBean? accountsReceivableBean = await k8Repository.accountsReceivableInfoData(maps: {"cmCode": action});
        if (accountsReceivableBean.status == 1) {
          mapsResult.addAll({action: accountsReceivableBean.data ?? []});
        } else {
          mapsFail.addAll({action: accountsReceivableBean.msg ?? ""});
        }
      }
      emit(RincosResultState(resultData: mapsResult, mapsFail: mapsFail));
    });

    on<WaiPanZhanBiEvent>((event, emit) async {
      //  需要查询多个表
      emit(const WaiPanZhanBiLoadingState());

      ThirdPartyBean? thirdPartyBean = await k8Repository.thirdPartyData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // 第三方
      CmsTicketBean? cmsBean = await k8Repository.cmsTicketData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // cms票据

      LocalDeliveryStatisticsBean? localDeliveryStatisticsBean =
          await k8Repository.localDeliveryStatisticsVotingData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // 同城本地表1
      IndependentStatisticalBean? independentStatisticalBean =
          await k8Repository.independentStatisticalIdentificationData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // 同城本地表 -》電商件入場數細分
      if (localDeliveryStatisticsBean.status == 1 && independentStatisticalBean.status == 1) {
        for (int i = 0; i < localDeliveryStatisticsBean.data!.length; i++) {
          var sCANDATELocalDelivery = localDeliveryStatisticsBean.data?[i].sCANDATE;
          independentStatisticalBean.data!.forEach((element) {
            if (sCANDATELocalDelivery == element.dateTime) {
              localDeliveryStatisticsBean.data?[i].oNLINEBUSSINS = element.total; // 电商件入场等雨另一个总和
              double percentage = double.parse(localDeliveryStatisticsBean.data![i].sIGNRATEONLINE.toString().replaceAll('%', '')) / 100;
              double result = percentage * localDeliveryStatisticsBean.data![i].oNLINEBUSSINS!;
              localDeliveryStatisticsBean.data?[i].sIGNONLINE = result.toInt();
              //sIGNONLINE.toString())),  // // 签收
              // sIGNRATEONLINE.toString())),   签收率
              //總件數(入場)
              localDeliveryStatisticsBean.data![i].cOUNTBUSSINS =
                  localDeliveryStatisticsBean.data![i].oNLINEBUSSINS! + localDeliveryStatisticsBean.data![i].lOCALBUSSINS!;
              //簽收(整體)
              double percentage2 = double.parse(localDeliveryStatisticsBean.data![i].sIGNCOUNTONLINE.toString().replaceAll('%', '')) / 100;
              double result2 = percentage2 * localDeliveryStatisticsBean.data![i].cOUNTBUSSINS!;
              localDeliveryStatisticsBean.data![i].sIGNCOUNT = result2.toInt();
            }
          });
        }
      }
      if (cmsBean.status == 1 && localDeliveryStatisticsBean.status == 1) {
        // 进行数据替换 cms 与本地签收表1
        for (int i = 0; i < cmsBean.data!.length; i++) {
          var cmsData = cmsBean.data![i].gROUPDATE;
          localDeliveryStatisticsBean.data!.forEach((element) {
            if (cmsData == element.sCANDATE) {
              // 时间相同，替换
              cmsBean.data![i].tCCOUNT = element.lOCALBUSSINS;
              cmsBean.data![i].dSCOUNT = element.oNLINEBUSSINS;
              cmsBean.data![i].aLLCOUNT = cmsBean.data![i].tCCOUNT! + cmsBean.data![i].dSCOUNT!; // F +B
            }
          });
        }
      }

      var aF = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.aF ?? 0));
      var tCDDC = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCDDC ?? 0));
      var tCHVAN = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCHVAN ?? 0));
      var dSDDC = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSDDC ?? 0));
      var dSHVAN = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSHVAN ?? 0));
      var tCJ = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.tCJ ?? 0));
      var dSJ = thirdPartyBean!.data!.fold(0, (value, element) => value + (element.dSJ ?? 0));
      int zhanBizCount = aF + tCDDC + tCHVAN + dSDDC + dSHVAN + tCJ + dSJ;
      int cmsCount = 0;
      if (cmsBean.status == 1 && localDeliveryStatisticsBean.status == 1) {
        cmsCount = cmsBean.data!.fold(0, (value, element) => value + (element.aLLCOUNT ?? 0));
      }
      dynamic percent = zhanBizCount / cmsCount;
      // 转成百分比，保留两位小数
      percent = (percent * 100).toStringAsFixed(2) + "%";
      WaiPanZhanBiBean waiPanZhanBiBean = WaiPanZhanBiBean(
          aF: aF, tCDDC: tCDDC, tCHVAN: tCHVAN, dSDDC: dSDDC, dSHVAN: dSHVAN, tCJ: tCJ, dSJ: dSJ, total: zhanBizCount, cmsTotal: cmsCount, percent: percent);
      if (thirdPartyBean.status == 1) {
        emit(WaiPanZhanBiSuccessState(
          localDeliveryStatisticsBean: localDeliveryStatisticsBean,
          independentStatisticalBean: independentStatisticalBean,
          thirdPartyBean: thirdPartyBean,
          cmsTicketBean: cmsBean,
          waiPanZhanBiBean: waiPanZhanBiBean,
        ));
      } else {
        emit(WaiPanZhanBiFailureState(failureMsg: thirdPartyBean.msg.toString()));
      }
    });

    on<TaoPiaoXiaoShouShiYongEvent>((event, emit) => taoPiaoXiaoShouShiYongEvent(event, emit));

    on<MonthFeeAndTaoPiaoEvent>((event, emit) => monthFeeAndTaoPiao(event, emit));
    // 电商表数据解析
    on<DianShangDataEvent>((event, emit) => dianShangData(event, emit));
    // 汇总数据解析
    on<HuiZongDataEvent>((event, emit) => huiZongData(event, emit));
    // 调整审核
    on<AdjustmentAuditEvent>((event, emit) => adjustAudit(event, emit));
  }

  taoPiaoXiaoShouShiYongEvent(event, emit) async {
    emit(const TaoPiaoXiaoShouShiYongLoadingState());
    // DailyInformationBean? dailyInformationBean = await k8Repository.dailyInfoData(mapsResult: {"startTime": event.startDate, "endTime": event.endDate, "custType": event.custType});
    DailyInformationBean? dailyInformationBean =
        await k8Repository.dailyInfoData(maps: {"startTime": event.startDate, "endTime": event.endDate, "custType": "套票客"});
    if (dailyInformationBean.status == 1) {
      // 如果客户名称为 . 或者空，则重新查询，改为length的判断
      if (dailyInformationBean.data != null) {
        for (int i = 0; i < dailyInformationBean.data!.length; i++) {
          dynamic value = dailyInformationBean.data![i];
          if (value.cMNAME == "." || value.cMNAME == "") {
            CustomerBean customerBean = await k8Repository.queryCustomerData(maps: {"cmCode": value.cMCODE});
            dailyInformationBean.data![i].cMNAME = "${customerBean.data?.single.cmEname}";
          }
        }
      }
    }
    // 分别计算直客和加盟商的数量
    int zhuKesCount = 0;
    int jiaMansCount = 0;
    if (dailyInformationBean.status == 1) {
      for (var value1 in dailyInformationBean.data!) {
        if (value1.bGNAME.toString().contains("CXC")) {
          zhuKesCount += value1.bLBILLNUM!;
        } else {
          jiaMansCount += value1.bLBILLNUM!;
        }
      }
      printRed("直客数量：$zhuKesCount");
      printRed("加盟商数量：$jiaMansCount");
      // 获取
      DailyVoteBean? dailyVoteBean = await k8Repository.dailyVoteData(maps: {"startTime": event.startDate, "endTime": event.endDate});
      dynamic tpZK = dailyVoteBean.data?.fold(0, (value, element) => element.tPZK! + value);
      dynamic tPJM = dailyVoteBean.data?.fold(0, (value, element) => element.tPJM! + value);
      printRed("直客金额  ${tpZK}");
      printRed("加盟商金额 ${tPJM}");

      dynamic resultData = {
        "current_date": "${event.startDate.substring(0, 7)}",
        "zhuKesCount": zhuKesCount,
        "jiaMansCount": jiaMansCount,
        "tpZK": tpZK,
        "tPJM": tPJM
      };
      emit(TaoPiaoXiaoShouShiYongSuccessState(resultData: resultData, dailyInformationBean: dailyInformationBean, dailyVoteBean: dailyVoteBean));
    }
  }

  monthFeeAndTaoPiao(event, emit) async {
    CustomerAdditionBean? customerAdditionBean = await k8Repository.customerAdditionTerminateReportData(
        maps: {"startTime": event.startDate, "endTime": event.endDate, "startTimeTwo": event.startDate, "endTimeTwo": "2100-01-01"});

    // 原始数据把OCS 去掉
    customerAdditionBean.customerBean!.removeWhere((element) => element.bGCODE == "OCS");

    List<CustomerBeanData> cData = [];
    List<CustomerBeanData> nData = [];
    List<CustomerBeanData> bData = [];

    if (customerAdditionBean.status == 1) {
      for (var element in customerAdditionBean.customerBean!) {
        if (element.bCCODE == "127") {
          continue;
        }
        if (element.cMREMARK.toString().contains("轉套票")) {
          continue;
        }
        if (element.cMNAME.toString().contains("测试") || element.cMNAME.toString().contains("測試")) {
          continue;
        }

        // 群组名称
        var bgNameTemp = element.cMCODE.toString();
        var customerGroup = getGroupName(element.cMCODE.toString(), bgNameTemp);
        element.t = customerGroup;
        element.t = bgNameTemp;

        element.cMADDRESS = element.cMADDRESS.toString().replaceAll("\n", "").replaceAll("\t", " ").trim();
        element.cMREMARK = element.cMREMARK.toString().replaceAll("\n", "").replaceAll("\t", " ").trim();
        element.cMREMARK = element.cMREMARK.toString().replaceAll(RegExp(r'\s+'), ' ');

        if (element.cMREMARK.toString().contains("客户介绍") || element.cMREMARK.toString().contains("客戶介紹")) {
          element.cMREMARK = "客户介绍";
        }
        // 分类
        if (element.cMTYPE == "宝箱" || element.cMCODE.toString().contains("CXCB")) {
          // 宝箱
          element.cMTYPE = "宝箱";
          bData.add(element);
        } else {
          if (element.cMTYPE == "套票客") {
            String e = ((element.bLCOST == null) ? "0" : element.bLCOST).toString();
            String f = ((element.bLBILLNUM == null) ? "0" : element.bLBILLNUM).toString();
            element.u = "";
            if (e != "0" && f != "0") {
              element.u = (double.parse(e) / double.parse(f)).toStringAsFixed(1);
            }
            if (element.u == "NaN") {
              element.u = 0;
            }

            if (element.bLBILLNUM == null || element.bLCOST == null) {
              continue;
            }
            // 套票客
            cData.add(element);
          } else if (element.cMTYPE == "月費客") {
            String h = ((element.cMMONTHCOST == null) ? "0" : element.cMMONTHCOST).toString();
            String i = ((element.cMORDERNUM == null) ? "0" : element.cMORDERNUM).toString();
            element.u = "";
            if (h != "0" && i != "0") {
              element.u = (double.parse(h) / double.parse(i)).toStringAsFixed(1);
            }
            if (element.u == "NaN") {
              element.u = 0;
            }

            // 判断是否有金额和柯打数值 CM_MONTHCOST  CM_ORDERNUM
            if (double.parse(element.cMMONTHCOST.toString()) == 0 && double.parse(element.cMORDERNUM.toString()) == 0) {
              continue;
            }
            // 非套票客
            nData.add(element);
          }
        }
      }
    }
    emit(MonthFeeAndTaoPiaoSuccessState(originDataTemp: customerAdditionBean.customerBean ?? [], cDataTemp: cData, nDataTemp: nData, bDataTemp: bData));
  }

  dianShangData(event, emit) async {
    emit(const DianShangDataLoadingState());
    int month = event.month;
    // 根据当前月份获取需要的数据
    List<int> monthCounts = [];
    // 计算所需的月份索引
    for (int i = 0; i < 5; i++) {
      // 过去4个月 + 当前月
      int index = (month - 1 - i + 12) % 12; // 处理0索引和负值的情况
      monthCounts.add(index + 1);
    }
    OtherOnlineRetailersBean otherOnlineRetailersBean =
        await k8Repository.otherOnlineRetailersComparisonData(maps: {"startTime": event.startDate, "endTime": event.endDate, "month": month});
    List<OtherOnlineData> otherOnlineData = [];
    if (otherOnlineRetailersBean.status == 1) {
      otherOnlineData = otherOnlineRetailersBean.data!;
    }
    // 查询code 为202的所有客户信息
    CustomerBean customerBean202 = await k8Repository.queryCustomerData(maps: {"bcCode": "202"});
    List<String> accountCodes = customerBean202.data?.map((e) => e.cmCode.toString()).toList() ?? []; // 所有的客户编号
    // 分析数据分类
    List<OtherOnlineData> existenceData = [];
    List<OtherOnlineData> nData = [];
    for (var element in otherOnlineData) {
      if (accountCodes.contains(element.cMCODE)) {
        existenceData.add(element);
      } else {
        nData.add(element);
      }
    }
    emit(DianShangDataSuccessState(existenceData: existenceData, nData: nData, monthCounts: monthCounts));
  }

  // 数据汇总
  huiZongData(event, emit) async {
    emit(const HuiZongDataLoadingState());
    /* 新增月費客數據 */
    List<CustomerBeanData> nDataTemp = event.nDataTemp;
    // 套票总额
    dynamic monthZE = 0;
    // 套票数量
    dynamic monthZongCount = nDataTemp.length;
    // 加盟商
    dynamic jmsMonthZETotal = 0;
    dynamic jmsMonthZECount = 0;
    // 直客
    dynamic zhuKesMonthTotal = 0;
    dynamic zhuKesMonthCount = 0;
    for (var element in nDataTemp) {
      monthZE += element.cMMONTHCOST ?? 0;
      if (!element.bCNAME.toString().contains("快遞中心有限公司")) {
        jmsMonthZETotal += element.cMMONTHCOST ?? 0;
        jmsMonthZECount++;
      } else {
        zhuKesMonthTotal += element.cMMONTHCOST ?? 0;
        zhuKesMonthCount++;
      }
    }
    // 加盟商总额除以平台总额
    dynamic jmsMonthPercent = (jmsMonthZETotal / monthZE).toStringAsFixed(2).toString();
    // 直客总额除以平台总额
    dynamic zhuKesMonthPercent = (zhuKesMonthTotal / monthZE).toStringAsFixed(2).toString();

    Map<String, dynamic> monthData = {};
    if (monthZE != 0) {
      monthData = {
        "monthZE": "\$$monthZE",
        "monthZongCount": monthZongCount,
        "jmsMonthZE": "\$$jmsMonthZETotal",
        "jmsMonthCount": jmsMonthZECount,
        "jmsMonthPercent": jmsMonthPercent,
        "zhuKesMonthZE": "\$$zhuKesMonthTotal",
        "zhuKesMonthCount": zhuKesMonthCount,
        "zhuKesMonthPercent": zhuKesMonthPercent
      };
    }

    /*   套票客新增數據   */
    List<CustomerBeanData> cDataTemp = event.cDataTemp;
    // 套票总额
    dynamic taopiaoZE = 0;
    // 套票数量
    dynamic taopiaoZongCount = cDataTemp.length;
    // 加盟商
    dynamic jmsZETotal = 0;
    dynamic jmsZECount = 0;
    // 直客
    dynamic zhuKesTotal = 0;
    dynamic zhuKesCount = 0;

    for (var element in cDataTemp) {
      taopiaoZE += element.bLCOST ?? 0;
      if (!element.bCNAME.toString().contains("快遞中心有限公司")) {
        jmsZETotal += element.bLCOST ?? 0;
        jmsZECount++;
      } else {
        zhuKesTotal += element.bLCOST ?? 0;
        zhuKesCount++;
      }
    }

    // 加盟商总额除以平台总额
    dynamic jmsPercent = (jmsZETotal / taopiaoZE).toStringAsFixed(2).toString();
    // 直客总额除以平台总额
    dynamic zhuKesPercent = (zhuKesTotal / taopiaoZE).toStringAsFixed(2).toString();

    Map<String, dynamic> tpData = {};
    if (taopiaoZE != 0) {
      tpData = {
        "tpAllZE": "\$$taopiaoZE",
        "tpAllCount": taopiaoZongCount,
        "jmsZE": "\$$jmsZETotal",
        "jmsCount": jmsZECount,
        "jmsPercent": jmsPercent,
        "zhuKesZE": "\$$zhuKesTotal",
        "zhuKesCount": zhuKesCount,
        "zhuKesPercent": zhuKesPercent,
      };
    }

    // 判断是否为跨月份查询
    List<Map<String, dynamic>> reqDate = [
      // {"startTime": event.startDate, "endTime": event.endDate}
    ];

    // 同月情况下，查询时间点为当前日期到周三的数据。
    // if (event.startDate.split("-")[1] == event.endDate.split("-")[1]) {
    // 获取开始时间
    DateTime startDate = DateTime.parse(event.startDate);
    DateTime endDate = DateTime.parse(event.endDate);

    while (startDate.isBefore(endDate)) {
      // 周几
      int weekday = startDate.weekday;

      print("startDate: ${startDate.toString()}   结束日期");
      print("weekday: $weekday");
      if (weekday == 1) {
        String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";
        startDate = startDate.add(Duration(days: 2));
        // 判断一下结束日期是否为下个月，如果是则把结束日期改为这个月的最后一天
        String endDateStr = "";
        if (startDateStr.split("-")[1] == startDate.month.toString().padLeft(2, '0')) {
          // 同月
          endDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 23:59:59";
        } else {
          // 获取上个月的最后一天
          DateTime lastDay = DateTime(startDate.year, startDate.month, 1);
          lastDay = lastDay.subtract(Duration(days: 1));
          endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
        }
        reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
        startDate = startDate.add(Duration(days: 1));
      } else if (weekday == 2) {
        String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";
        startDate = startDate.add(Duration(days: 1));
        // 判断一下结束日期是否为下个月，如果是则把结束日期改为这个月的最后一天
        String endDateStr = "";
        if (startDateStr.split("-")[1] == startDate.month.toString().padLeft(2, '0')) {
          // 同月
          endDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 23:59:59";
        } else {
          // 获取上个月的最后一天
          DateTime lastDay = DateTime(startDate.year, startDate.month, 1);
          lastDay = lastDay.subtract(Duration(days: 1));
          endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
        }
        reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
        startDate = startDate.add(Duration(days: 1));
      } else if (weekday == 3) {
        String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";
        startDate = startDate.add(Duration(days: 0));
        String endDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 23:59:59";
        reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
        startDate = startDate.add(Duration(days: 1));
      } else if (weekday == 4) {
        String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";
        startDate = startDate.add(Duration(days: 6));
        // 判断一下结束日期是否为下个月，如果是则把结束日期改为这个月的最后一天
        String endDateStr = "";
        if (startDateStr.split("-")[1] == startDate.month.toString().padLeft(2, '0')) {
          // 同月
          endDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 23:59:59";
        } else {
          // 获取上个月的最后一天
          DateTime lastDay = DateTime(startDate.year, startDate.month, 1);
          lastDay = lastDay.subtract(Duration(days: 1));
          endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
        }

        reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
        startDate = startDate.add(Duration(days: 1));
      } else if (weekday == 5) {
        String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";
        startDate = startDate.add(Duration(days: 5));
        // 判断一下结束日期是否为下个月，如果是则把结束日期改为这个月的最后一天
        String endDateStr = "";
        if (startDateStr.split("-")[1] == startDate.month.toString().padLeft(2, '0')) {
          // 同月
          endDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 23:59:59";
        } else {
          // 获取上个月的最后一天
          DateTime lastDay = DateTime(startDate.year, startDate.month, 1);
          lastDay = lastDay.subtract(Duration(days: 1));
          endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
        }
        reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
        startDate = startDate.add(Duration(days: 1));
      } else if (weekday == 6) {
        String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";
        startDate = startDate.add(Duration(days: 4));
        // 判断一下结束日期是否为下个月，如果是则把结束日期改为这个月的最后一天
        String endDateStr = "";
        if (startDateStr.split("-")[1] == startDate.month.toString().padLeft(2, '0')) {
          // 同月
          endDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 23:59:59";
        } else {
          // 获取上个月的最后一天
          DateTime lastDay = DateTime(startDate.year, startDate.month, 1);
          lastDay = lastDay.subtract(Duration(days: 1));
          endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
        }
        reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
        startDate = startDate.add(Duration(days: 1));
      } else if (weekday == 7) {
        String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";
        startDate = startDate.add(Duration(days: 3));
        // 判断一下结束日期是否为下个月，如果是则把结束日期改为这个月的最后一天
        String endDateStr = "";
        if (startDateStr.split("-")[1] == startDate.month.toString().padLeft(2, '0')) {
          // 同月
          endDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 23:59:59";
        } else {
          // 获取上个月的最后一天
          DateTime lastDay = DateTime(startDate.year, startDate.month, 1);
          lastDay = lastDay.subtract(Duration(days: 1));
          endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
        }
        reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
        startDate = startDate.add(Duration(days: 1));
      }
    }

    print("日期 :${reqDate}");
    // }

    if (event.startDate.split("-")[1] != event.endDate.split("-")[1]) {
      String startDate = event.startDate;
      // last day
      DateTime endDate = DateTime.parse(event.endDate);
      DateTime lastDay = DateTime(endDate.year, endDate.month, 1);
      lastDay = lastDay.subtract(Duration(days: 1));
      String endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
      reqDate.add({"startTime": startDate, "endTime": endDateStr});

      DateTime lastDayEnd = DateTime(endDate.year, endDate.month, 1);
      String lastDayEndStr = "${lastDayEnd.year}-${lastDayEnd.month.toString().padLeft(2, '0')}-${lastDayEnd.day.toString().padLeft(2, '0')} 00:00:00";
      reqDate.add({"startTime": lastDayEndStr, "endTime": event.endDate});
    } else {
      reqDate.add({"startTime": event.startDate, "endTime": event.endDate});
    }

    List<Map<String, dynamic>> resultAllData = [];
    for (var valueDate in reqDate) {
      DailyInformationBean? dailyInformationBean =
          await k8Repository.dailyInfoData(maps: {"startTime": valueDate['startTime'], "endTime": valueDate['endTime'], "custType": "套票客"});
      if (dailyInformationBean.status == 1) {
        if (dailyInformationBean.data != null) {
          for (int i = 0; i < dailyInformationBean.data!.length; i++) {
            dynamic value = dailyInformationBean.data![i];
            if (value.cMNAME == "." || value.cMNAME == "") {
              CustomerBean customerBean = await k8Repository.queryCustomerData(maps: {"cmCode": value.cMCODE});
              dailyInformationBean.data![i].cMNAME = "${customerBean.data?.single.cmEname}";
            }
          }
        }

        // 获取总收入（总）
        dynamic totalIncome = dailyInformationBean?.data?.fold(0, (element, value) => element + value.bLCOST!);
        // 总条数（总）
        dynamic totalCount = dailyInformationBean?.data?.length;
        // 套票数量（总）
        dynamic taoPiaoCount = dailyInformationBean?.data?.fold(0, (element, value) => element + (value.bLBILLNUM ?? 0));
        // 加盟商总额
        dynamic jiaMansJE = dailyInformationBean?.data?.fold(0, (element, value) {
          if (!value.bGNAME.toString().contains("CXC")) {
            return element + value.bLCOST!;
          } else {
            return element;
          }
        });
        // 加盟商客户
        int jiaMansCount = 0;
        // 判断加盟商数量，条件是       bGNAME 不包含CXC
        for (var element in dailyInformationBean.data!) {
          if (!element.bGNAME.toString().contains("CXC")) {
            jiaMansCount++;
          }
        }
        // 加盟商套票数量
        dynamic taoPiaoCountJiaMans = dailyInformationBean?.data?.fold(0, (element, value) {
          if (!value.bGNAME.toString().contains("CXC")) {
            return element + value.bLBILLNUM!;
          } else {
            return element;
          }
        });
        // 直客数量
        int zhuKesCount = totalCount - jiaMansCount;
        // 直客金额
        dynamic tpZKJE = dailyInformationBean?.data?.fold(0, (element, value) {
          if (value.bGNAME.toString().contains("CXC")) {
            return element + value.bLCOST!;
          } else {
            return element;
          }
        });
        // 直客套票数量
        dynamic tpZKCount = dailyInformationBean?.data?.fold(0, (element, value) {
          if (value.bGNAME.toString().contains("CXC")) {
            return element + value.bLBILLNUM!;
          } else {
            return element;
          }
        });

        Map<String, dynamic> resultData = {
          "selectDate": "${valueDate['startTime']}-${valueDate['endTime']}",
          "totalIncome": totalIncome,
          "totalCount": totalCount,
          "taoPiaoCount": taoPiaoCount,
          "jiaMansJE": jiaMansJE,
          "jiaMansCount": jiaMansCount,
          "taoPiaoCountJiaMans": taoPiaoCountJiaMans,
          "jiaMansPercent": (jiaMansJE / totalIncome * 100).toStringAsFixed(1) + "%",
          "zhuKesCount": zhuKesCount,
          "tpZKJE": tpZKJE,
          "tpZKCount": tpZKCount,
          "zhuKesPercent": (tpZKJE / totalIncome * 100).toStringAsFixed(1) + "%",
        };
        resultAllData.add(resultData);
      }
    }
    emit(HuiZongDataSuccessState(resultData: resultAllData, tpData: tpData, monthData: monthData));
  }

  //调整审核
  adjustAudit(event, emit) async {
    emit(const AdjustmentAuditLoadingState());

    // 判断是否为跨月份查询
    // 判断是否为跨月份查询
    List<Map<String, dynamic>> reqDate = [
      {"startTime": event.startDate, "endTime": event.endDate}
    ];
    if (event.startDate.split("-")[1] != event.endDate.split("-")[1]) {
      reqDate.clear();
      String startDate = event.startDate;
      // last day
      DateTime endDate = DateTime.parse(event.endDate);
      DateTime lastDay = DateTime(endDate.year, endDate.month, 1);
      lastDay = lastDay.subtract(Duration(days: 1));
      String endDateStr = "${lastDay.year}-${lastDay.month.toString().padLeft(2, '0')}-${lastDay.day.toString().padLeft(2, '0')} 23:59:59";
      reqDate.add({"startTime": "${startDate} 00:00:00", "endTime": endDateStr});

      DateTime lastDayEnd = DateTime(endDate.year, endDate.month, 1);
      String lastDayEndStr = "${lastDayEnd.year}-${lastDayEnd.month.toString().padLeft(2, '0')}-${lastDayEnd.day.toString().padLeft(2, '0')} 00:00:00";
      reqDate.add({"startTime": lastDayEndStr, "endTime": "${event.endDate} 23:59:59"});
    } else {
      reqDate.clear();
      DateTime startDate = DateTime.parse(event.startDate);
      String startDateStr = "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00";

      DateTime endDate = DateTime.parse(event.endDate);
      String endDateStr = "${endDate.year}-${endDate.month.toString().padLeft(2, '0')}-${endDate.day.toString().padLeft(2, '0')} 23:59:59";

      reqDate.add({"startTime": startDateStr, "endTime": endDateStr});
    }

    String auditType = event.auditType;
    String auditState = event.auditState;

    Map<String, dynamic> resultAllData = {};

    // 查询当前的时间范围数据
    for (var value in reqDate) {
      AdjustInvoiceBean adjustInvoiceBean = await k8Repository
          .adjustInvoiceData(maps: {"startTime": value["startTime"], "endTime": value["endTime"], "auditType": auditType, "auditState": auditState}); // 第三方
      if (adjustInvoiceBean.status == 1) {
        // 删除测试数据 ，驳回的数据
        adjustInvoiceBean.data?.removeWhere((e) => e.rEVIEWERFLAGSTATE == "審核駁回");
        adjustInvoiceBean.data?.removeWhere((e) => e.mODIFYREMARK == "測試" || e.mODIFYREMARK == "测试");
        // 加盟商
        List<String> jmCode = [
          "52",
          "53",
          "56",
          "58",
          "85",
          "93",
          "44",
          "90",
          "91",
          "33",
          "83",
          "82",
          "29",
          "28",
          "84",
          "70",
          "72",
          "74",
          "76",
          "68",
          "71",
          "73",
          "77",
          "75",
          "42",
          "43",
          "46",
          "47",
          "2020",
          "96",
          "97",
          "95"
        ];
        // 获取当前时间的月份
        DateTime now = DateTime.now();
        int currentMonth = DateTime(now.year, now.month - 1, now.day).month;
        // 申请时间
        adjustInvoiceBean.data?.removeWhere((e) {
          int day = DateTime.parse(e.cREATEDATE.toString()).day;
          // 15号之前，月份等于上个月
          if (day < 15 && currentMonth == int.parse(e.iMONTH.toString())) {
            return true;
          }
          return false;
        });

        // 15号之前  ，跳过当月数据（上个月）
        // 15号之后  ，所有数据都要处理
        // 发票调整

        // 加盟商累加数据
        double jmOldMonthTotal = 0;
        double jmNewMonthTotal = 0;
        double jmAdjustedAmount = 0;
        // 直客累加数据
        double zkOldMonthTotal = 0;
        double zkNewMonthTotal = 0;
        double zkAdjustedAmount = 0;

        // 数据分类
        List<AdjustInvoiceData> dataD20 = [];
        List<AdjustInvoiceData> dataX20 = [];

        // 总体数据
        for (AdjustInvoiceData value in adjustInvoiceBean.data ?? []) {
          if (jmCode.contains(value.bCCODE.toString())) {
            // 加盟商
            jmOldMonthTotal += value.oLDMONEY ?? 0;
            jmNewMonthTotal += value.nOWMONEY ?? 0;
            jmAdjustedAmount += value.adjustedAmount ?? 0;
          } else {
            // cxc 直客
            zkOldMonthTotal += value.oLDMONEY ?? 0;
            zkNewMonthTotal += value.nOWMONEY ?? 0;
            zkAdjustedAmount += value.adjustedAmount ?? 0;
          }
          if ((value.nOWMONEY ?? 0) < -20) {
            dataD20.add(value);
          } else {
            dataX20.add(value);
          }
        }
        // 合計
        double totalOldMonthTotal = jmOldMonthTotal + zkOldMonthTotal;
        double totalNewMonthTotal = jmNewMonthTotal + zkNewMonthTotal;
        double totalAdjustedAmount = jmAdjustedAmount + zkAdjustedAmount;
        // 每月發票調整匯總
        Map<String, dynamic> invoiceAdjustmentData = {
          "zkOldMonthTotal": zkOldMonthTotal,
          "zkNewMonthTotal": zkNewMonthTotal,
          "zkAdjustedAmount": zkAdjustedAmount,
          "jmOldMonthTotal": jmOldMonthTotal,
          "jmNewMonthTotal": jmNewMonthTotal,
          "jmAdjustedAmount": jmAdjustedAmount,
          "totalOldMonthTotal": totalOldMonthTotal,
          "totalNewMonthTotal": totalNewMonthTotal,
          "totalAdjustedAmount": totalAdjustedAmount,
        };
        // 时间是key，数据是value
        resultAllData.addAll({
          "${value["startTime"]}-${value["endTime"]}": {
            "invoiceAdjustmentData": invoiceAdjustmentData,
            "adjustmentAuditD20Data": dataD20,
            "adjustmentAuditX20Data": dataX20
          }
        });
      }
    }

    // 查询整个月的数据  整月-----------------------------------------------------------------------------------------------------------------------
    Map<String, dynamic> resultWholeMonthData = {};
    List<Map<String, dynamic>> reqWholeMonthDate = [];
    if (event.startDate.split("-")[1] != event.endDate.split("-")[1]) {
      DateTime startWholeMonth = DateTime.parse(event.startDate); // 开始时间
      DateTime endWholeMonth = DateTime.parse(event.endDate); // 结束时间
      // 判断两个时间之间有多少个月
      int monthCount = (endWholeMonth.year - startWholeMonth.year) * 12 + (endWholeMonth.month - startWholeMonth.month);
      // 循环月份
      reqWholeMonthDate.clear();
      for (int i = 0; i <= monthCount; i++) {
        // 设置日期的日为1
        DateTime startChildMonth = DateTime(startWholeMonth.year, startWholeMonth.month + i, 1);
        String startChildMonthStr = "${startChildMonth.year}-${startChildMonth.month.toString().padLeft(2, '0')}-01 00:00:00";
        // 设置为最后一天
        String endChildMonthStr = "";
        if (i == monthCount) {
          // 最后一天为传入的数据
          DateTime endChildMonth = DateTime.parse(event.endDate);
          endChildMonthStr = "${endChildMonth.year}-${endChildMonth.month.toString().padLeft(2, '0')}-${endChildMonth.day.toString().padLeft(2, '0')} 23:59:59";
        } else {
          DateTime endChildMonth = DateTime(startChildMonth.year, startChildMonth.month + 1, 1).subtract(Duration(days: 1));
          endChildMonthStr = "${endChildMonth.year}-${endChildMonth.month.toString().padLeft(2, '0')}-${endChildMonth.day.toString().padLeft(2, '0')} 23:59:59";
        }
        reqWholeMonthDate.add({"startTime": startChildMonthStr, "endTime": endChildMonthStr});
      }
    } else {
      reqWholeMonthDate.clear();

      DateTime startWholeMonth = DateTime.parse(event.startDate); // 开始时间
      DateTime endChildMonth = DateTime.parse(event.endDate); // 结束时间

      // 设置日期的日为1
      DateTime startChildMonth = DateTime(startWholeMonth.year, startWholeMonth.month, 1);
      String startChildMonthStr = "${startChildMonth.year}-${startChildMonth.month.toString().padLeft(2, '0')}-01 00:00:00";

      String endChildMonthStr =
          "${endChildMonth.year}-${endChildMonth.month.toString().padLeft(2, '0')}-${endChildMonth.day.toString().padLeft(2, '0')} 23:59:59";
      reqWholeMonthDate.add({"startTime": startChildMonthStr, "endTime": endChildMonthStr});
    }

    for (var value in reqWholeMonthDate) {
      AdjustInvoiceBean adjustInvoiceBean = await k8Repository
          .adjustInvoiceData(maps: {"startTime": value["startTime"], "endTime": value["endTime"], "auditType": auditType, "auditState": auditState}); // 第三方
      if (adjustInvoiceBean.status == 1) {
        // 删除测试数据 ，驳回的数据
        adjustInvoiceBean.data?.removeWhere((e) => e.rEVIEWERFLAGSTATE == "審核駁回");
        adjustInvoiceBean.data?.removeWhere((e) => e.mODIFYREMARK == "測試" || e.mODIFYREMARK == "测试");
        // 加盟商
        List<String> jmCode = [
          "52",
          "53",
          "56",
          "58",
          "85",
          "93",
          "44",
          "90",
          "91",
          "33",
          "83",
          "82",
          "29",
          "28",
          "84",
          "70",
          "72",
          "74",
          "76",
          "68",
          "71",
          "73",
          "77",
          "75",
          "42",
          "43",
          "46",
          "47",
          "2020",
          "96",
          "97",
          "95"
        ];
        // 获取当前时间的月份
        DateTime now = DateTime.now();
        int currentMonth = DateTime(now.year, now.month - 1, now.day).month;
        // 申请时间
        adjustInvoiceBean.data?.removeWhere((e) {
          int day = DateTime.parse(e.cREATEDATE.toString()).day;
          // 15号之前，月份等于上个月
          if (day < 15 && currentMonth == int.parse(e.iMONTH.toString())) {
            return true;
          }
          return false;
        });

        // 15号之前  ，跳过当月数据（上个月）
        // 15号之后  ，所有数据都要处理
        // 发票调整

        // 加盟商累加数据
        double jmOldMonthTotal = 0;
        double jmNewMonthTotal = 0;
        double jmAdjustedAmount = 0;
        // 直客累加数据
        double zkOldMonthTotal = 0;
        double zkNewMonthTotal = 0;
        double zkAdjustedAmount = 0;

        // 总体数据
        for (AdjustInvoiceData value in adjustInvoiceBean.data ?? []) {
          if (jmCode.contains(value.bCCODE.toString())) {
            // 加盟商
            jmOldMonthTotal += value.oLDMONEY ?? 0;
            jmNewMonthTotal += value.nOWMONEY ?? 0;
            jmAdjustedAmount += value.adjustedAmount ?? 0;
          } else {
            // cxc 直客
            zkOldMonthTotal += value.oLDMONEY ?? 0;
            zkNewMonthTotal += value.nOWMONEY ?? 0;
            zkAdjustedAmount += value.adjustedAmount ?? 0;
          }
        }
        // 合計
        double totalOldMonthTotal = jmOldMonthTotal + zkOldMonthTotal;
        double totalNewMonthTotal = jmNewMonthTotal + zkNewMonthTotal;
        double totalAdjustedAmount = jmAdjustedAmount + zkAdjustedAmount;
        // 每月發票調整匯總
        Map<String, dynamic> invoiceAdjustmentData = {
          "zkOldMonthTotal": zkOldMonthTotal,
          "zkNewMonthTotal": zkNewMonthTotal,
          "zkAdjustedAmount": zkAdjustedAmount,
          "jmOldMonthTotal": jmOldMonthTotal,
          "jmNewMonthTotal": jmNewMonthTotal,
          "jmAdjustedAmount": jmAdjustedAmount,
          "totalOldMonthTotal": totalOldMonthTotal,
          "totalNewMonthTotal": totalNewMonthTotal,
          "totalAdjustedAmount": totalAdjustedAmount,
        };
        // 时间是key，数据是value
        resultWholeMonthData.addAll({
          "${value["startTime"]}-${value["endTime"]}": {"invoiceAdjustmentData": invoiceAdjustmentData}
        });
      }
    }

    emit(AdjustmentAuditSuccessState(resultAllData: resultAllData, resultWholeMonthData: resultWholeMonthData));
  }
}
